<?php

namespace app\api\controller;

use app\admin\model\Avideo as Avideos;
use app\admin\model\ExamItem;
use app\admin\model\ExamRecord;
use app\common\controller\Api;
use app\common\controller\Redis;
use fast\Http;
use think\Db;
use app\common\controller\aes\WXBizDataCrypt;
/**
 * 示例接口
 */
class Demo extends Api
{

    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取我的视频列表,不需要用户的ID
     */
    public function getrandom()
    {
        $tiyan=[49,50,51,52];
        $page = $this->request->param('page')??1;
        $num = $this->request->param('num')??5;
        $vmodel = new \app\admin\model\Avideo();
        $data = $vmodel::with([
            'com' => function($query) {
                $query->order('id','desc') ;
            }
        ])->with('com,category')
            ->order('weigh asc')
            ->select()->each(function ($item){
                if ($item['com']){
                    $item['comments'] = sizeof($item['com']);
                    //查询评论人信息
                    foreach ($item['com'] as $k => $v) {
                        $user = \app\admin\model\Auser::get($v['auser_id']);
                        $item['com'][$k]['name'] = $user['name'];
                        $item['com'][$k]['avatar'] = $user['avatar'];
                    }
                    $coms=$item['com'];
                    $commms=[];
                    foreach ($item['com'] as $k => $v){
                        if($item['com'][$k]['pid']>0){
                            unset($item['com'][$k]);
                        }else{
                            $arr=[];
                            foreach ($coms as $ve) {
                                if ($ve['pid'] == $item['com'][$k]['id']) {
                                    $arr[] = $ve;
                                };
                            };
                            $item['com'][$k]['children']=$arr;
                            $commms[]=$item['com'][$k];
                        }
                    }
                    $item['com']=$commms;
                }else{
                    $item['comments'] = 0;
                }
                $item['article_title'] = Db::name('article')->where('avideo_id',$item['id'])->order('id desc')->value('title');
                $item['iscolles'] = 0;
                $item['iszan'] = 0;
                if(empty($item['article_title'])){
                    $item['article_title']='';
                }
                //判断当前请求的用户是否点赞该视频
                return $item;
            })->toArray();
        foreach ($data as $k=>$v){
            $cates=explode(',',$data[$k]['cate_id']);
            if(empty(array_intersect($tiyan,$cates))){
                unset($data[$k]);
            }
        }
        if(!empty($data)){
            $data=page_array($num,$page,$data);
        }
        $this->success('成功',$data);
    }

    /*
     * 获取单个视频的相关信息
     * */
    public function singlev()
    {
        $vid = $this->request->param('vid');
        $vmodel = new \app\admin\model\Avideo();
        $data = $vmodel::with('com,category')
            ->where('avideo.id',$vid)
            ->order('ctime desc')
            ->find();
        if (!$data)$this->error('无数据');
            if (sizeof($data['com']) > 0){
                //查询评论人信息
                foreach ($data['com'] as $k=>$v){
                    $user = \app\admin\model\Auser::get($v['auser_id']);
                    if(empty($user)){
                        unset($data['com'][$k]);
                    }else{
                        $data['com'][$k]['name'] = $user['name'];
                        $data['com'][$k]['avatar'] = $user['avatar'];
                    }
                }
                $data['comments'] = sizeof($data['com']);
            }else{
                $data['comments'] = 0;
            }
        $this->success('成功',$data);
    }

    /*
     * redis测试
     * */
    public function aa()
    {

        $redis = Redis::getInstance()->getRedisConn();
        $redis->hSet('user_4','67','1');
//        $redis->hSet('user_12','7','0');
        $re = $redis->hGetAll('user_4');
//        $re = $redis->del('user_4');//删除所有key下的东西
        dump($re);
        echo sizeof($re);
    }

    /*
     * 获取考试题
     * @param $exam_id int 考试id
     * */
    public function exam_items($exam_id)
    {
        //查询考试试题
        $ret['exam_item'] = Db::name('exam_item')->where('exam_id',$exam_id)->select()->toArray();
        foreach ( $ret['exam_item'] as $k=>$v ){

            $ret['exam_item'][$k]['Lstate'] = false;

            $ret['exam_item'][$k]['answers'][0]['key'] = 'A';
            $ret['exam_item'][$k]['answers'][0]['value'] = $v['A'];
            $ret['exam_item'][$k]['answers'][0]['ischeck'] = false;



            $ret['exam_item'][$k]['answers'][1]['key'] = 'B';
            $ret['exam_item'][$k]['answers'][1]['value'] = $v['B'];
            $ret['exam_item'][$k]['answers'][1]['ischeck'] = false;


            $ret['exam_item'][$k]['answers'][2]['key'] = 'C';
            $ret['exam_item'][$k]['answers'][2]['value'] = $v['C'];
            $ret['exam_item'][$k]['answers'][2]['ischeck'] = false;


            if($v['D']==''){
                unset($ret['exam_item'][$k]['D']);
            }else{
                $ret['exam_item'][$k]['answers'][3]['key'] = 'D';
                $ret['exam_item'][$k]['answers'][3]['value'] = $v['D'];
                $ret['exam_item'][$k]['answers'][3]['ischeck'] = false;
            }
            if ($v['E'] == ''){
                unset($ret['exam_item'][$k]['E']);
            }else{
                $ret['exam_item'][$k]['answers'][4]['key'] = 'E';
                $ret['exam_item'][$k]['answers'][4]['value'] = $v['E'];
                $ret['exam_item'][$k]['answers'][4]['ischeck'] = false;
            }
            if ($v['F'] == ''){
                unset($ret['exam_item'][$k]['F']);
            }else{
                $ret['exam_item'][$k]['answers'][5]['key'] = 'F';
                $ret['exam_item'][$k]['answers'][5]['value'] = $v['F'];
                $ret['exam_item'][$k]['answers'][5]['ischeck'] = false;
            }
        }
        return $ret['exam_item'];
    }

    /*
     * 获取某个考试的答题记录
     * */
    public function answers()
    {
        $exam_id = 1;//考试id
        $uid = 1;
        $remodel = new ExamRecord();
        $rec = $remodel::get(['auser_id'=>$uid,'exam_id' => $exam_id]);
        if ($rec){
            $arr = json_decode($rec->record,1);
            $exitem = new ExamItem();
            foreach ($arr as  $k=>$v){
                $arr[$k]['info'] = $exitem::get($v['id']);
            }
            $rec->record = $arr;
            $this->success('成功',$rec);
        }
        $this->error('查无此考试');
    }

    /*
     * 获取某个视频下的评论信息
     * */
    public function videping()
    {
        $vid = $this->request->param('vid');
//        $com = Db::name('comments')
        $vmodel = new \app\admin\model\Comments();
        $com = $vmodel::with('yauser')
            ->where('avideo_id',$vid)
            ->order('id desc')
            ->select()->each(function ($item){
                $item['ctime']=date('Y-m-d',strtotime($item['ctime']));
                return $item;
            })->toArray();
        $coms=$vmodel::with('yauser')
            ->where('avideo_id',$vid)
            ->order('id asc')
            ->select()->each(function ($item){
                $item['ctime']=date('Y-m-d',strtotime($item['ctime']));
                return $item;
            })->toArray();
        if ($com){
            $commms=[];
            foreach ($com as $k=>$v){
                $com[$k]['userinfo'] = Db::name('auser')->where('id',$v['auser_id'])->field('id,name,avatar')->find();
                if($com[$k]['pid']>0){
                    unset($com[$k]);
                }else{
                    $arr=[];
                    foreach ($coms as $ve) {
                        if ($ve['pid'] == $com[$k]['id']) {
                            $ve['userinfo'] = Db::name('auser')->where('id',$ve['auser_id'])->field('id,name,avatar')->find();
                            if(empty($ve['talk_pid'])){
                                $ve['talk_pid']=0;
                                $ve['talk_userinfo']=[];
                            }else{
                                $talkcomments=Db::name('comments')->where('id',$ve['talk_pid'])->find();
                                $ve['talk_userinfo'] = Db::name('auser')->where('id',$talkcomments['auser_id'])->field('id,name,avatar')->find();
                            }
                            $arr[] = $ve;
                        };
                    };
                    $com[$k]['children']=$arr;
                    $commms[]=$com[$k];
                }
            }
            $this->success('成功',$commms);
        }
        $this->error('无评论');
    }

    /*
     * 获取考试列表
     * */
    public function exams()
    {
        $uid = 1;
        $cid = Db::name('auser')->where('id',$uid)->value('cate_id');
        //根据cid 查询未通过中的未测试的考试
        $exmodel = new ExamRecord();
        //已通过--- 已测试及格的考试
        $pass = $exmodel::with('getExamInfo')
            ->where('auser_id',$uid)
            ->where('ispass','0')
            ->select()->each(function ($item){
                $item->record = json_decode($item->record,1);
            });
        //未通过--- 未测试 / 不及格的 考试
        $this->success('',$pass);
    }

    /*
     * 生成一个测试的token
     * */
    public function tos()
    {
        $payload = array('iss'=>'admin','iat'=>time(),'exp'=>time()+72000000000,'nbf'=>time(),'sub'=>'www.admin.com','uid'=>4);
        $token = Jwt::getToken($payload);
        $this->success('',$token);
    }

    /*
     * 测试 uni获取unionid
     * */
    public function union()
    {
        $data = $this->request->param();
        $APPID = 'wxe106dceb5c64084a';
        $pc      = new WXBizDataCrypt($APPID, $data['sessionKey']);
        $errCode = $pc->decryptData($data['encryptedData'], $data['iv'], $datas);
        if ($errCode == 0) {
            $this->success('成功',$datas);
        } else {
            $this->error('失败');
        }
    }
    /*
     * 获取sessionkey
     * */
    public function sessionkey()
    {
          $APPID = 'wxe106dceb5c64084a';
          $APPSECRET = '0ba74311a403430b8390d9b70ef5cff3';

        $code = $this->request->param('code');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $APPID . '&secret=' . $APPSECRET . '&js_code=' . $code . '&grant_type=authorization_code';
        $arr = Http::get($url);
        //获取openid
        $arr = json_decode($arr, true);

        //获取当前的openid
        $openId = $arr['session_key'];
        return $openId;
    }

}
